const carouselConfig = [
    3000,  // 第一个轮播项的切换时间（毫秒）
    3000, // 第二个轮播项的切换时间（毫秒）
];

let carousel;
let vh;
let newsTitle;
let newsContainer;
let videos;

document.addEventListener('DOMContentLoaded', function() {
    carousel = new bootstrap.Carousel(document.getElementById('mainCarousel'), {
        interval: false,
        wrap: true
    });
    
    vh = window.innerHeight;
    newsTitle = document.querySelector('.home-news-title');
    newsContainer = document.querySelector('.news-container');
    videos = document.querySelectorAll('#mainCarousel video');
    
    window.addEventListener('scroll', updateElements);
    
    // 初始化时处理第一个视频
    handleCarouselSlide();
    
    // 监听轮播切换事件
    document.getElementById('mainCarousel').addEventListener('slid.bs.carousel', handleCarouselSlide);
});

function handleCarouselSlide() {
    // 暂停所有视频并重置到开始位置
    videos.forEach(video => {
        video.pause();
        video.currentTime = 0;
    });

    const activeItem = document.querySelector('.carousel-item.active');
    const activeVideo = activeItem.querySelector('video');
    const currentIndex = Array.from(activeItem.parentElement.children).indexOf(activeItem);
    const interval = carouselConfig[currentIndex];
    
    // 如果当前轮播项包含视频，播放它
    if (activeVideo) {
        activeVideo.play().catch(error => {
            console.error("视频播放失败:", error);
        });
    }
    
    // 设置下一次自动切换的时间
    setTimeout(() => {
        carousel.next();
    }, interval);
}

function updateElements() {
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    const progress = Math.min(Math.max((scrollTop / vh) * 2, 0), 1);
    
    // 仅在非移动端设备上调整标题颜色和容器位置
    if (window.innerWidth > 768) {
        const titleColor = `rgb(${255 - progress * 255}, ${255 - progress * 255}, ${255 - progress * 255})`;
        if (newsTitle) {
            newsTitle.style.color = titleColor;
        }
        
        const marginTop = -150 + (progress * 150);
        if (newsContainer) {
            newsContainer.style.marginTop = `${marginTop}px`;
        }
    } else {
        // 在移动端设备上，重置为CSS中定义的默认样式
        if (newsTitle) {
            newsTitle.style.color = '';
        }
        
        if (newsContainer) {
            newsContainer.style.marginTop = '';
        }
    }
}